package audit

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/audit"
	auditReq "counter-help/admin/server/model/audit/request"
	"counter-help/admin/server/model/common/response"
	"counter-help/admin/server/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"io"
	"os"
	"path/filepath"
)

type EducationVerificationApi struct{}

// CreateOrUpdateEducationVerification  创建学历认证
func (api *EducationVerificationApi) CreateOrUpdateEducationVerification(c *gin.Context) {
	// 获取上传的学历证书文件（允许文件未上传）
	certificateFile, certificateFileHeader, err := c.Request.FormFile("certificate")
	var certificatePath string // 定义路径变量，未上传文件时保持为空
	if err != nil {
		fmt.Println("学历证书文件未上传或获取失败:", err)
		certificateFile = nil // 明确表示未上传文件
	} else {
		defer certificateFile.Close() // 确保文件在函数结束后被关闭
	}

	// 绑定请求中的 JSON 数据到结构体
	var educationReq auditReq.EducationVerification
	fmt.Printf("educationReq: %+v", educationReq)

	if err := c.ShouldBind(&educationReq); err != nil {
		fmt.Println("部分数据未绑定，非必填字段允许为空:", err)
	} else {
		fmt.Println("数据绑定成功:", educationReq)
	}

	// 如果上传了文件，则定义存储路径并保存文件
	if certificateFile != nil && certificateFileHeader != nil {
		userID := utils.GetUserID(c)
		certificateDir := fmt.Sprintf("uploads/education_verifications/%d", userID)
		certificatePath = fmt.Sprintf("%s/certificate_%s", certificateDir, filepath.Base(certificateFileHeader.Filename))

		// 检查并创建目录
		if err := os.MkdirAll(certificateDir, os.ModePerm); err != nil {
			global.GVA_LOG.Error("创建存储目录失败!", zap.Error(err))
			response.FailWithMessage("创建存储目录失败", c)
			return
		}

		// 清空目录中的所有文件
		files, err := os.ReadDir(certificateDir)
		if err != nil {
			global.GVA_LOG.Error("读取存储目录失败!", zap.Error(err))
			response.FailWithMessage("读取存储目录失败", c)
			return
		}
		for _, file := range files {
			if err := os.Remove(fmt.Sprintf("%s/%s", certificateDir, file.Name())); err != nil {
				global.GVA_LOG.Error("删除旧文件失败", zap.Error(err))
				response.FailWithMessage("删除旧文件失败", c)
				return
			}
		}

		// 手动保存文件数据到服务器
		out, err := os.Create(certificatePath)
		if err != nil {
			global.GVA_LOG.Error("学历证书保存失败!", zap.Error(err))
			response.FailWithMessage("学历证书保存失败", c)
			return
		}
		defer out.Close()

		// 将文件内容从 certificateFile 拷贝到目标文件
		if _, err := io.Copy(out, certificateFile); err != nil {
			global.GVA_LOG.Error("文件写入失败", zap.Error(err))
			response.FailWithMessage("文件写入失败", c)
			return
		}
	}

	// 构建学历认证记录
	education := audit.EducationVerification{
		UserID:          utils.GetUserID(c),
		SchoolName:      educationReq.SchoolName,
		Degree:          educationReq.Degree,
		GraduationDate:  educationReq.GraduationDate,
		CertificatePath: certificatePath, // 未上传文件时为 ""
		IsReviewed:      false,
	}

	// 尝试查找现有记录并进行更新或创建
	if err := educationVerificationService.CreateOrUpdateEducationVerification(education); err != nil {
		global.GVA_LOG.Error("创建或更新学历认证失败!", zap.Error(err))
		response.FailWithMessage("创建或更新学历认证失败", c)
		return
	}

	response.OkWithMessage("学历认证创建或更新成功", c)
}

// GetEducationVerification 获取学历认证信息
func (api *EducationVerificationApi) GetEducationVerification(c *gin.Context) {
	userID := utils.GetUserID(c)
	education, err := educationVerificationService.GetEducationVerificationByUserID(userID)
	if err != nil {
		global.GVA_LOG.Error("获取学历认证失败!", zap.Error(err))
		response.CommonFailWithMessage("获取学历认证失败", c)
		return
	}

	response.OkWithDetailed(education, "获取学历认证成功", c)
}

// ApproveEducationVerification 审核通过
func (api *EducationVerificationApi) ApproveEducationVerification(c *gin.Context) {
	var request struct {
		UserID uint `json:"userId" form:"userId" binding:"required"`
	}
	if err := c.ShouldBindJSON(&request); err != nil {
		response.FailWithMessage("数据绑定失败", c)
		return
	}
	// 调用服务更新学历认证状态为通过
	if err := educationVerificationService.ApproveEducation(request.UserID); err != nil {
		global.GVA_LOG.Error("学历认证审核通过失败!", zap.Error(err))
		response.FailWithMessage("学历认证审核通过失败", c)
		return
	}

	response.OkWithMessage("学历认证审核通过", c)
}

// RejectEducationVerification 审核不通过
func (api *EducationVerificationApi) RejectEducationVerification(c *gin.Context) {
	userID := utils.GetUserID(c)

	var rejectionData struct {
		RejectionReason string `json:"rejectionReason" form:"rejectionReason"`
	}

	if err := c.ShouldBindJSON(&rejectionData); err != nil {
		response.FailWithMessage("数据绑定失败", c)
		return
	}

	// 调用服务更新学历认证状态为不通过并设置驳回理由
	if err := educationVerificationService.RejectEducation(userID, rejectionData.RejectionReason); err != nil {
		global.GVA_LOG.Error("学历认证审核不通过失败!", zap.Error(err))
		response.FailWithMessage("学历认证审核不通过失败", c)
		return
	}

	response.OkWithMessage("学历认证审核不通过", c)
}

// GetPendingEducationVerifications 获取所有未审核的学历认证记录
func (api *EducationVerificationApi) GetPendingEducationVerifications(c *gin.Context) {
	pendingVerifications, err := educationVerificationService.GetPendingEducationVerifications()
	if err != nil {
		global.GVA_LOG.Error("获取未审核学历认证记录失败!", zap.Error(err))
		response.FailWithMessage("获取未审核学历认证记录失败", c)
		return
	}
	response.OkWithDetailed(pendingVerifications, "获取未审核学历认证记录成功", c)
}

// GetApprovedEducationVerifications 获取所有已审核的学历认证记录
func (api *EducationVerificationApi) GetApprovedEducationVerifications(c *gin.Context) {
	approvedVerifications, err := educationVerificationService.GetApprovedEducationVerifications()
	if err != nil {
		global.GVA_LOG.Error("获取已审核学历认证记录失败!", zap.Error(err))
		response.FailWithMessage("获取已审核学历认证记录失败", c)
		return
	}
	response.OkWithDetailed(approvedVerifications, "获取已审核学历认证记录成功", c)
}
